#include "definition.h"
#include "DocImportCmd.h"
#include "../Format/FormatHandler.h"
#include "../MagicDocConsole.h"

DocImportCmd::DocImportCmd(STRING path, STRING folder, MagicDocFrame* mainframe)
:m_path(path), m_folder(folder), m_mainFrame(mainframe)
{
    
}

bool DocImportCmd::Do()
{
    // copy the file into depot, and get new path of it
    m_newPath = DocInfoCenter::InstanceRef().CopyDoc(m_path, m_folder);

    // read the content of the file by using format handler
    FormatHandler* handler = MagicDocConsole::InstanceRef().SelectFormatHandler(m_newPath);
    if(!handler || !handler->DocImport(m_path))
    {
        wxMessageBox( wxT("Failed to import document!"), wxT("Error") );
        
        delete handler;
        return false;
    }
    m_content = handler->GetContent();

    // save infomation of this file
    DocInfomation info = DocInfoCenter::InstanceRef().ReadInfoFromFile(PATH(m_newPath));
    info.m_filePath = m_folder;
    DocInfoCenter::InstanceRef().SaveInfo(info);

    // create document
    Document* doc = MagicDocConsole::InstanceRef().OpenDoc( m_newPath );
    doc->SetContent( m_content );

    // update GUI
    m_mainFrame->InsertTreeFile(doc, info.m_fileName, info.m_filePath);

    delete handler;
    return true;   
}

bool DocImportCmd::Undo()
{
    return false;
}
